package com.example.pei.papa.activity;

import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.aurelhubert.ahbottomnavigation.AHBottomNavigation;
import com.aurelhubert.ahbottomnavigation.AHBottomNavigationAdapter;
import com.aurelhubert.ahbottomnavigation.AHBottomNavigationViewPager;
import com.example.pei.papa.tables.UserInfo;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.DownloadFileListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;


import com.example.pei.papa.R;
import com.example.pei.papa.adapter.tabbarViewPageAdapter;
import com.example.pei.papa.dialog.headChooseDialog;
import com.example.pei.papa.fragments.tabbarFragments;

import static com.example.pei.papa.utils.SnackbarUtil.ShowSnackbar;


public class MainActivity extends AppCompatActivity  {

    //private personalMenuFragment personalFragment;


    private Uri imageUri;

    private File cameraFile ;       //相机拍摄图片的文件

    private File coverOutputCropImage;   //封面裁剪后的文件，即上传到服务器中的文件
    private Uri  coverimageCropUri;             //上面这个文件的URL
    private String coverPath;         //选择的封面在本地的存储路径,如果是相机拍的图片，则为拍摄图片的存储路径，如果是相册选择的图片，则为选择的图片的路径
                                        // ，但最终裁剪后的路径不是这里，和下面的服务器下载到本地的位置相同
    private String localCoverPath; //封面从服务器下载到本地的位置


    private File headOutputCropImage;   //头像裁剪后的文件，即上传到服务器中的文件
    private Uri  headimageCropUri;             //上面这个文件的URL

    private static final int IMAGE_REQUEST_CODE = 0;
    private static final int CAMERA_REQUEST_CODE = 1;
    private static final int CROP_REQUEST_CODE = 3;


    private int coverWidth;
    private int coverHeight;




    private String headPath;//选择的头像在本地的存储路径，但最终裁剪后的路径不是这里，和下面的服务器下载到本地的位置相同
    private String localheadPath;//头像从服务器下载到本地的位置

    private headChooseDialog dialog;

    private int choosefor;//个人设置里对话框是为封面选择还是为头像选择  1为封面 ，2为头像

    private  BmobFile coverBmobFile;  //封面
    private  BmobFile headBmobFile;  //头像
    private String coverFileUrl; //封面在服务器中的url
    private String headFileUrl;//头像在服务器中的url
    private UserInfo currentUser;


    private tabbarFragments currentFragment;
    private AHBottomNavigationViewPager viewPager;
    private tabbarViewPageAdapter adapter;


    public interface downloadCoverListener{
        public void downloadCoverDone(String path);
    }
    public interface downloadHeadListener{
        public void downloadHeadDone(String path);
    }
    private downloadCoverListener coverDownloadListener;
    private downloadHeadListener  headDownloadListener;


    public UserInfo getCurrentUser(){return  currentUser;}
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        Bundle bundle = getIntent().getExtras();
        currentUser= bundle.getParcelable("currentUser");

        coverFileUrl=currentUser.getCoverFileUrl();
        headFileUrl=currentUser.getHeadFileUrl();

        initUi();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        } else {
            Uri u;
            switch (requestCode) {
                case IMAGE_REQUEST_CODE:
                    //判断手机系统版本号
                    if(Build.VERSION.SDK_INT>=19){
                        //4.4及以上系统使用这个方法处理图片
                        handleImageOnKitKat(data);
                    }else{
                        //4.4及以下系统使用这个方法处理图片
                        handleImageBeforeKitKat(data);
                    }
                    if(choosefor==1) {
                        if (Build.VERSION.SDK_INT >= 24) {
                            u = FileProvider.getUriForFile(MainActivity.this, "onlyid", new File(coverPath));
                        } else {
                            u = Uri.fromFile(new File(coverPath));
                        }
                        cropImageUri(u, CROP_REQUEST_CODE);
                    }
                    if(choosefor==2){
                        if (Build.VERSION.SDK_INT >= 24) {
                            u = FileProvider.getUriForFile(MainActivity.this, "onlyid", new File(headPath));
                        } else {
                            u = Uri.fromFile(new File(headPath));
                        }
                        cropImageUri(u, CROP_REQUEST_CODE);
                    }
                    break;

                case CAMERA_REQUEST_CODE:
                    if(choosefor==1) {//封面裁剪
                        if (Build.VERSION.SDK_INT >= 24) {
                            u = FileProvider.getUriForFile(MainActivity.this,"onlyid", new File(coverPath));
                        } else {
                            u = Uri.fromFile(new File(coverPath));
                        }
                        cropImageUri(u, CROP_REQUEST_CODE);
                    }
                    if(choosefor==2) {//头像裁剪
                        if (Build.VERSION.SDK_INT >= 24) {
                            u = FileProvider.getUriForFile(MainActivity.this,"onlyid", new File(headPath));
                        } else {
                            u = Uri.fromFile(new File(headPath));
                        }
                        cropImageUri(u, CROP_REQUEST_CODE);
                    }
                    break;
                case CROP_REQUEST_CODE:
                    if (data != null) {
                        if(choosefor==1)
                        {
                            if (coverimageCropUri != null) {
                                Bitmap bitmap = null;
                                try {
                                    // 先通过getContentResolver方法获得一个ContentResolver实例，
                                    // 调用openInputStream(Uri)方法获得uri关联的数据流stream
                                    // 把上一步获得的数据流解析成为bitmap
                                    bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(coverimageCropUri));
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                }
                                //将封面显示到屏幕上
                                currentFragment.getImageView_cover().setImageBitmap(bitmap);

                                //服务器中已经有封面，则应该删除
                                if (coverFileUrl != null) {
                                    BmobFile file = new BmobFile();
                                    file.setUrl(coverFileUrl);//此url是上传文件成功之后通过bmobFile.getUrl()方法获取的。
                                    file.delete(new UpdateListener() {
                                        @Override
                                        public void done(BmobException e) {
                                            if (e == null) {
                                                //删除成功，则上传新封面到服务器中
                                                upLoadCover();
                                            } else {
                                                if (e.getErrorCode() == 151) {
                                                    //uri错误,服务器没有此图片
                                                    coverFileUrl = null;
                                                    upLoadCover();
                                                }
                                                //Toast.makeText(MainActivity.this, "封面删除失败"+e.getErrorCode()+"   "+e.getMessage(), Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    });
                                } else {
                                    //服务器没有封面，直接上传
                                    upLoadCover();
                                }
                            }
                        }

                        if(choosefor==2)
                        {
                            if (headimageCropUri != null) {
                                Bitmap bitmap = null;
                                try {
                                    // 先通过getContentResolver方法获得一个ContentResolver实例，
                                    // 调用openInputStream(Uri)方法获得uri关联的数据流stream
                                    // 把上一步获得的数据流解析成为bitmap
                                    bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(headimageCropUri));
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                }
                                //将封面显示到屏幕上
                                currentFragment.getImageView_head().setImageBitmap(bitmap);

                                //服务器中已经有封面，则应该删除
                                if (headFileUrl != null) {
                                    BmobFile file = new BmobFile();
                                    file.setUrl(headFileUrl);//此url是上传文件成功之后通过bmobFile.getUrl()方法获取的。
                                    file.delete(new UpdateListener() {
                                        @Override
                                        public void done(BmobException e) {
                                            if (e == null) {
                                                //删除成功，则上传新封面到服务器中
                                                upLoadHead();
                                            } else {
                                                if (e.getErrorCode() == 151) {
                                                    //uri错误,服务器没有此图片
                                                    headFileUrl = null;
                                                    upLoadHead();
                                                }
                                                //Toast.makeText(MainActivity.this, "封面删除失败"+e.getErrorCode()+"   "+e.getMessage(), Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    });
                                } else {
                                    //服务器没有封面，直接上传
                                    upLoadHead();
                                }
                            }
                        }
                    }
                    break;
            }
        }
    }

    private void initUi(){
        AHBottomNavigation bottomNavigation = (AHBottomNavigation) findViewById(R.id.bottom_navigation);
        viewPager = (AHBottomNavigationViewPager) findViewById(R.id.view_pager);
        int[] tabColors = getApplicationContext().getResources().getIntArray(R.array.tab_colors);
        AHBottomNavigationAdapter navigationAdapter = new AHBottomNavigationAdapter(this, R.menu.bottom_navigation_menu_5);
        navigationAdapter.setupWithBottomNavigation(bottomNavigation, tabColors);
        bottomNavigation.setColored(true);

        bottomNavigation.setOnTabSelectedListener(new AHBottomNavigation.OnTabSelectedListener() {
            @Override
            public boolean onTabSelected(int position, boolean wasSelected) {

                if (currentFragment == null) {
                    currentFragment = adapter.getCurrentFragment();
                }

                if (wasSelected) {
                    currentFragment.refresh();
                    return true;
                }

                if (currentFragment != null) {
                    currentFragment.willBeHidden();
                }

                viewPager.setCurrentItem(position, false);

                if (currentFragment == null) {
                    return true;
                }

                currentFragment = adapter.getCurrentFragment();
                currentFragment.willBeDisplayed();

                if (position == 1) {

                } else {

                }

                return true;
            }
        });

        viewPager.setOffscreenPageLimit(4);
        adapter = new tabbarViewPageAdapter(getSupportFragmentManager());
        viewPager.setAdapter(adapter);
        currentFragment = adapter.getCurrentFragment();
    }

    //打开相册
    private void openAlbum(){
        Intent intent=new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent,IMAGE_REQUEST_CODE);
    }

    @TargetApi(19)
    private void handleImageOnKitKat(Intent data){
        if(data==null) return;
        String imagePath=null;
        Uri uri=data.getData();
        String a=uri.getAuthority();
        if(DocumentsContract.isDocumentUri(this,uri)){
            //如果是documents类型的uri，则通过document id处理
            String docId=DocumentsContract.getDocumentId(uri);
            if("com.android.providers.media.documents".equals(uri.getAuthority())){
                String id =docId.split(":")[1];  //解析出数字格式的id
                String selection= MediaStore.Images.Media._ID+"="+id;
                imagePath=getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
            }else if("com.android.providers.downloads.documents".equals(uri.getAuthority())){
                Uri contentUri= ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(docId));
            }
        }else if("content".equalsIgnoreCase(uri.getScheme())){
            //如果是content类型的uri，则使用普通方式处理
            imagePath=getImagePath(uri,null);
        }else if("file".equalsIgnoreCase(uri.getScheme())){
            //如果是file类型的uri，直接获取图片路径即可
            imagePath=uri.getPath();
        }

        if(choosefor==1) {
            coverPath = imagePath;
        }
        if(choosefor==2){
            headPath=imagePath;
        }

    }



    private void handleImageBeforeKitKat(Intent data){
        if(data==null) return;
        Uri uri=data.getData();
        String imagePath=getImagePath(uri,null);
        if(choosefor==1) {
            coverPath = imagePath;
        }
        if(choosefor==2){
            headPath=imagePath;
        }

    }
    private String getImagePath(Uri uri,String selection){
        String path=null;
        //通过uri和selection来获取真实的图片路径
        Cursor cursor=getContentResolver().query(uri,null,selection,null,null);
        if(cursor!=null){
            if(cursor.moveToFirst()){
                path=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }
    private void cropImageUri(Uri uri ,int requestCode) {
        if(choosefor==1) {
            coverOutputCropImage = new File(getExternalCacheDir(), "CoverImage" + currentUser.getMobilePhoneNumber() + ".jpg");
            try {
                if (coverOutputCropImage.exists()) {
                    coverOutputCropImage.delete();
                }
                coverOutputCropImage.createNewFile();
                //  coverCropPath=outputCropImage.getPath();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (Build.VERSION.SDK_INT >= 24) {
                coverimageCropUri = FileProvider.getUriForFile(MainActivity.this,
                        "onlyid", coverOutputCropImage);
            } else {
                coverimageCropUri = Uri.fromFile(coverOutputCropImage);
            }


            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setDataAndType(uri, "image/*");
            //下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
            intent.putExtra("crop", "true");
            // aspectX aspectY 是宽高的比例
            intent.putExtra("aspectX", coverWidth);
            intent.putExtra("aspectY", coverHeight);
            // outputX outputY 是裁剪图片宽高
            intent.putExtra("outputX", coverWidth);
            intent.putExtra("outputY", coverHeight);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.putExtra("scale", true);//黑边
            intent.putExtra("scaleUpIfNeeded", true);//黑边

            //设置输入图片格式
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            intent.putExtra("return-data", false);

            // Uri x=getUri();
            intent.putExtra(MediaStore.EXTRA_OUTPUT, coverimageCropUri);
            //是否关闭面部识别
            intent.putExtra("noFaceDetection", true); // no face detection

            //授权
            List<ResolveInfo> resInfoList = getPackageManager()
                    .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
            for (ResolveInfo resolveInfo : resInfoList) {
                String packageName = resolveInfo.activityInfo.packageName;
                grantUriPermission(packageName, coverimageCropUri, Intent.FLAG_GRANT_READ_URI_PERMISSION
                        | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            }
            //启动
            startActivityForResult(intent, requestCode);
        }

        if(choosefor==2) {
            headOutputCropImage = new File(getExternalCacheDir(), "HeadImage" + currentUser.getMobilePhoneNumber() + ".jpg");
            try {
                if (headOutputCropImage.exists()) {
                    headOutputCropImage.delete();
                }
                headOutputCropImage.createNewFile();
                //  coverCropPath=outputCropImage.getPath();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (Build.VERSION.SDK_INT >= 24) {
                headimageCropUri = FileProvider.getUriForFile(MainActivity.this,
                        "onlyid", headOutputCropImage);
            } else {
                headimageCropUri = Uri.fromFile(headOutputCropImage);
            }


            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setDataAndType(uri, "image/*");
            //下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
            intent.putExtra("crop", "true");
            // aspectX aspectY 是宽高的比例
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            // outputX outputY 是裁剪图片宽高
            intent.putExtra("outputX",300 );
            intent.putExtra("outputY",300 );
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.putExtra("scale", true);//黑边
            intent.putExtra("scaleUpIfNeeded", true);//黑边

            //设置输入图片格式
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            intent.putExtra("return-data", false);

            // Uri x=getUri();
            intent.putExtra(MediaStore.EXTRA_OUTPUT, headimageCropUri);
            //是否关闭面部识别
            intent.putExtra("noFaceDetection", true); // no face detection

            //授权
            List<ResolveInfo> resInfoList = getPackageManager()
                    .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
            for (ResolveInfo resolveInfo : resInfoList) {
                String packageName = resolveInfo.activityInfo.packageName;
                grantUriPermission(packageName, headimageCropUri, Intent.FLAG_GRANT_READ_URI_PERMISSION
                        | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            }
            //启动
            startActivityForResult(intent, requestCode);
        }

    }


    private void DialogDismiss(){
        dialog.dismiss();
    }

    //到相册或者相机选择新封面
    public void chooseImage(int way,int width,int height){
        choosefor=way;
        if(choosefor==1){
            //选择的是封面
            coverWidth=width;
            coverHeight=height;

            View view = getLayoutInflater().inflate(R.layout.photo_choose_dialog, null);
            dialog = new headChooseDialog(this, R.style.transparentFrameWindowStyle,new headChooseDialog.LeaveMyDialogListener(){
                @Override
                public void onClick(View view) {
                    switch (view.getId()){
                        case R.id.btn_c:
                            DialogDismiss();
                            break;
                        case R.id.btn_g:
                            if(ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
                                ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
                            }else{
                                openAlbum();
                            }
                            DialogDismiss();
                            break;
                        case R.id.btn_t:
                            cameraFile=new File(getExternalCacheDir(),"tmpCameraImage"+currentUser.getMobilePhoneNumber()+".jpg");
                            try {
                                if(cameraFile.exists()){
                                    cameraFile.delete();
                                }
                                cameraFile.createNewFile();
                                coverPath=cameraFile.getPath();
                            }catch (IOException e){
                                e.printStackTrace();
                            }
                            if(Build.VERSION.SDK_INT>=24){
                                imageUri= FileProvider.getUriForFile(MainActivity.this,
                                        "onlyid",cameraFile);
                            }else {
                                imageUri= Uri.fromFile(cameraFile);
                            }
                            // 启动相机
                            Intent intent=new Intent("android.media.action.IMAGE_CAPTURE");
                            intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
                            startActivityForResult(intent,CAMERA_REQUEST_CODE);
                            DialogDismiss();
                            break;
                    }
                }
            });
            dialog.setContentView(view, new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT));
            Window window = dialog.getWindow();
            // 设置显示动画
            window.setWindowAnimations(R.style.main_menu_animstyle);
            WindowManager.LayoutParams wl = window.getAttributes();
            wl.x = 0;
            wl.y = getWindowManager().getDefaultDisplay().getHeight();
            // 以下这两句是为了保证按钮可以水平满屏
            wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
            wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;

            // 设置显示位置
            dialog.onWindowAttributesChanged(wl);
            // 设置点击外围解散
            dialog.setCanceledOnTouchOutside(true);
            dialog.show();
        }
        if(choosefor==2){
            //选择的是头像
            View view = getLayoutInflater().inflate(R.layout.photo_choose_dialog, null);
            dialog = new headChooseDialog(this, R.style.transparentFrameWindowStyle,new headChooseDialog.LeaveMyDialogListener(){
                @Override
                public void onClick(View view) {
                    switch (view.getId()){
                        case R.id.btn_c:
                            DialogDismiss();
                            break;
                        case R.id.btn_g:
                            if(ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
                                ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
                            }else{
                                openAlbum();
                            }
                            DialogDismiss();
                            break;
                        case R.id.btn_t:
                            cameraFile=new File(getExternalCacheDir(),"tmpCameraImage"+currentUser.getMobilePhoneNumber()+".jpg");
                            try {
                                if(cameraFile.exists()){
                                    cameraFile.delete();
                                }
                                cameraFile.createNewFile();
                                headPath=cameraFile.getPath();
                            }catch (IOException e){
                                e.printStackTrace();
                            }
                            if(Build.VERSION.SDK_INT>=24){
                                imageUri= FileProvider.getUriForFile(MainActivity.this,
                                        "onlyid",cameraFile);
                            }else {
                                imageUri= Uri.fromFile(cameraFile);
                            }
                            // 启动相机
                            Intent intent=new Intent("android.media.action.IMAGE_CAPTURE");
                            intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
                            startActivityForResult(intent,CAMERA_REQUEST_CODE);
                            DialogDismiss();
                            break;
                    }
                }
            });
            dialog.setContentView(view, new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT));
            Window window = dialog.getWindow();
            // 设置显示动画
            window.setWindowAnimations(R.style.main_menu_animstyle);
            WindowManager.LayoutParams wl = window.getAttributes();
            wl.x = 0;
            wl.y = getWindowManager().getDefaultDisplay().getHeight();
            // 以下这两句是为了保证按钮可以水平满屏
            wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
            wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;

            // 设置显示位置
            dialog.onWindowAttributesChanged(wl);
            // 设置点击外围解散
            dialog.setCanceledOnTouchOutside(true);
            dialog.show();
        }
    }

    private void upLoadCover(){
        coverBmobFile = new BmobFile(coverOutputCropImage);
        coverBmobFile.uploadblock(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if(e==null) {
                    coverFileUrl=coverBmobFile.getFileUrl();
                    currentUser.setCoverFileUrl(coverFileUrl);
                    currentUser.update(currentUser.getObjectId(),new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            if(e==null){
                                ShowSnackbar(findViewById(R.id.coordinatorlayout),"封面设置成功~","#FFAF70","#ffffff",16);
                            }else{
                                ShowSnackbar(findViewById(R.id.coordinatorlayout)," 信息更新失败","#FFAF70","#ffffff",16);
                            }
                        }
                    });
                }else {
                    Toast.makeText(MainActivity.this, "封面上传失败"+e.getErrorCode()+"   "+e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        });
    }
    private void upLoadHead(){
        headBmobFile = new BmobFile(headOutputCropImage);
        headBmobFile.uploadblock(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if(e==null) {
                    headFileUrl=headBmobFile.getFileUrl();
                    currentUser.setHeadFileUrl(headFileUrl);
                    currentUser.update(currentUser.getObjectId(),new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            if(e==null){
                                ShowSnackbar(findViewById(R.id.coordinatorlayout),"头像设置成功~","#FFAF70","#ffffff",16);

                            }else{
                                ShowSnackbar(findViewById(R.id.coordinatorlayout)," 信息更新失败","#FFAF70","#ffffff",16);
                            }
                        }
                    });
                }else {
                    Toast.makeText(MainActivity.this, "头像上传失败"+e.getErrorCode()+"   "+e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    public void downloadCoverFile(downloadCoverListener listener){
        coverDownloadListener=listener;

        //coverFileUrl 为空怎么办
        if(coverFileUrl==null){
            return;
        }
        BmobFile file=new BmobFile("CoverImage"+currentUser.getMobilePhoneNumber()+".jpg","",coverFileUrl);
        //允许设置下载文件的存储路径，默认下载文件的目录为：context.getApplicationContext().getCacheDir()+"/bmob/"
        File saveFile = new File(getExternalCacheDir(), file.getFilename());
        file.download(saveFile, new DownloadFileListener() {
            @Override
            public void onStart() {
                //Toast.makeText(MainActivity.this, "开始下载", Toast.LENGTH_SHORT).show();
            }
            @Override
            public void done(String savePath,BmobException e) {
                if(e==null){
                 //   Toast.makeText(MainActivity.this, "下载成功 保存路径:"+savePath, Toast.LENGTH_SHORT).show();
                    localCoverPath=savePath;
                    coverDownloadListener.downloadCoverDone(localCoverPath);
                }else{
                //    Toast.makeText(MainActivity.this, "下载失败"+e.getErrorCode()+"   "+e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
            @Override
            public void onProgress(Integer value, long newworkSpeed) {
            }

        });
    }

    public void downloadHeadFile(downloadHeadListener listener){
        headDownloadListener=listener;

        //coverFileUrl 为空怎么办
        if(headFileUrl==null){
            return;
        }
        BmobFile file=new BmobFile("HeadImage"+currentUser.getMobilePhoneNumber()+".jpg","",headFileUrl);
        //允许设置下载文件的存储路径，默认下载文件的目录为：context.getApplicationContext().getCacheDir()+"/bmob/"
        File saveFile = new File(getExternalCacheDir(), file.getFilename());
        file.download(saveFile, new DownloadFileListener() {
            @Override
            public void onStart() {
                //Toast.makeText(MainActivity.this, "开始下载", Toast.LENGTH_SHORT).show();
            }
            @Override
            public void done(String savePath,BmobException e) {
                if(e==null){
                    //   Toast.makeText(MainActivity.this, "下载成功 保存路径:"+savePath, Toast.LENGTH_SHORT).show();
                    localheadPath=savePath;
                    headDownloadListener.downloadHeadDone(localheadPath);
                }else{
                    //    Toast.makeText(MainActivity.this, "下载失败"+e.getErrorCode()+"   "+e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
            @Override
            public void onProgress(Integer value, long newworkSpeed) {
            }

        });
    }



}